package com.sunda.spmsuser.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmsuser.entity.SpmsUser;
import com.sunda.spmsuser.entity.SpmsUserRole;
import com.sunda.spmsuser.entity.SpmsUserWhs;
import com.sunda.spmsuser.entity.SpmsUserWorkshop;
import com.sunda.spmsuser.mapper.SpmsUserMapper;
import com.sunda.spmsuser.mapper.SpmsUserRoleMapper;
import com.sunda.spmsuser.mapper.SpmsUserWhsMapper;
import com.sunda.spmsuser.mapper.SpmsUserWorkshopMapper;
import com.sunda.spmsuser.service.ISpmsUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * SPMS用户信息表 服务实现类
 * </p>
 *
 * @author Wayne
 * @since 2021-01-25
 */
@Service
public class SpmsUserServiceImpl extends ServiceImpl<SpmsUserMapper, SpmsUser> implements ISpmsUserService {

    @Autowired
    SpmsUserMapper spmsUserMapper;

    @Autowired
    SpmsUserRoleMapper userRoleMapper;

    @Autowired
    SpmsUserWhsMapper userWhsMapper;

    @Autowired
    SpmsUserWorkshopMapper userWorkshopMapper;

    @Override
    public SpmsUser getByUserId(String userId) {
        try {
            if (StringUtils.isEmpty(userId)){
                return null;
            }
            return spmsUserMapper.getByUserId(userId);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public IPage<SpmsUser> spmsUserList(Page<SpmsUser> page) {
        try {
            return spmsUserMapper.selectPage(page, new QueryWrapper<>());
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<SpmsUser> getAllSpmsUserList() {
        return spmsUserMapper.selectList(null);
    }

    /**
     * {
     * 	"userInfo": {
     * 		"userId": "20001",
     * 		"loginPassword": "57697a33709a708ea59183af587593d2",
     * 		"workId": "20001",
     * 		"lastName": "20001",
     * 		"telephone": "13866668888",
     * 		"mobile": "13866668888",
     * 		"email": "sunda@sunda.com",
     * 		"positionId": "11",
     * 		"positionName": "position name",
     * 		"deptId": "123",
     * 		"deptName": "dept name",
     * 		"subcompanyId": "1234",
     * 		"subcompanyName": "subcompany id",
     * 		"company": "company",
     * 		"branchPoint": "12345",
     * 		"branchLine": "123456",
     * 		"managerId": "10000",
     * 		"managerName": "10000",
     * 		"oaStatus": "1",
     * 		"spmsStatus": "1"
     *        },
     * 	    "userRole": [{
     * 		    "uuid": "161556d97ae44139ad21659c5fb98e00",
     * 		    "roleId": "1001"
     *        }],
     * 	    "userWhs": [{
     * 		    "werks": "CN01",
     * 		    "whsLocationCode": "1061"
     *      }],
     * 	    "userWorkshop": [{
     * 		    "werks": "GH01",
     * 		    "workshopCode": "1002"
     *    }]
     * }
     * 新建用户，保存用户个人信息，及关联的角色、工厂、仓库、车间信息
     * @param doc
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult createSpmsUser(JSONObject doc, String MDPassword) {
        try {
            JSONObject userInfo = doc.getJSONObject("userInfo");
            String userId = userInfo.getString("userId");

            /** 创建用户个人信息，个人信息创建成功才能创建用户配置项信息 */
            int resp = createUser(userInfo, MDPassword);
            if (resp == 0){
                return ResponseResult.error("用户新增或更新失败");
            }

            /** 创建用户角色关系数据 */
            createUserRole(doc.getJSONArray("userRole"), userId);

            /** 创建用户-仓库关系数据 */
            createUserWhs(doc.getJSONArray("userWhs"), userId);

            /** 创建用户-车间关系数据 */
            createUserWorkshop(doc.getJSONArray("userWorkshop"), userId);

            return ResponseResult.success();
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.error();
        }
    }

    int createUser(JSONObject userInfo, String MDPassword){
        SpmsUser spmsUser = new SpmsUser();
        spmsUser.setUserId(userInfo.getString("userId"));
        spmsUser.setWorkId(userInfo.getString("workId"));
        spmsUser.setLastName(userInfo.getString("lastName"));
        spmsUser.setTelephone(userInfo.getString("telephone"));
        spmsUser.setMobile(userInfo.getString("mobile"));
        spmsUser.setEmail(userInfo.getString("email"));
        spmsUser.setPositionId(userInfo.getString("positionId"));
        spmsUser.setPositionName(userInfo.getString("positionName"));
        spmsUser.setDeptId(userInfo.getString("deptId"));
        spmsUser.setDeptName(userInfo.getString("deptName"));
        spmsUser.setSubcompanyId(userInfo.getString("subcompanyId"));
        spmsUser.setSubcompanyName(userInfo.getString("subcompanyName"));
        spmsUser.setCompany(userInfo.getString("company"));
        spmsUser.setBranchPoint(userInfo.getString("branchPoint"));
        spmsUser.setBranchLine(userInfo.getString("branchLine"));
        spmsUser.setManagerId(userInfo.getString("managerId"));
        spmsUser.setManagerName(userInfo.getString("managerName"));
        spmsUser.setOaStatus(userInfo.getString("oaStatus"));
        spmsUser.setSpmsStatus(userInfo.getString("spmsStatus"));
        if (spmsUserMapper.selectOne(new QueryWrapper<SpmsUser>().eq("WORK_CODE", spmsUser.getUserId())) != null){
            /** 对已存在用户则只执行用户更新操作，忽略 loginPassword-密码字段更新 */
            return spmsUserMapper.update(spmsUser, new QueryWrapper<SpmsUser>().eq("WORK_CODE", spmsUser.getUserId()));
        }
        /** 不存在的用户信息，则执行新建用户操作，此时给出默认的加密密码 */
        spmsUser.setLoginPassword(MDPassword);
        return spmsUserMapper.insert(spmsUser);
    }

    void createUserRole(JSONArray array, String userId){
        /** 创建用户-角色关系数据 */
        userRoleMapper.delete(new QueryWrapper<SpmsUserRole>().eq("WORK_CODE", userId));
        if (array.size() > 0){
            for (int i = 0; i < array.size(); i ++){
                JSONObject doc = array.getJSONObject(i);
                SpmsUserRole userRole = new SpmsUserRole();
                userRole.setUuid(UUID.randomUUID().toString().replaceAll("-","").toLowerCase());
                userRole.setUserId(userId);
                //userRole.setRoleId(doc.getString("roleId"));
                userRole.setRoleUuid(doc.getString("uuid"));
                userRoleMapper.insert(userRole);
            }

//            for (Object roleId : array){
//                SpmsUserRole userRole = new SpmsUserRole();
//                userRole.setUuid(UUID.randomUUID().toString().replaceAll("-","").toLowerCase());
//                userRole.setUserId(userId);
//                userRole.setRoleId(roleId.toString());
//                userRoleMapper.insert(userRole);
//            }
        }
    }
    void createUserWhs(JSONArray array, String userId){
        /** 创建用户-仓库关系数据 */
        userWhsMapper.delete(new QueryWrapper<SpmsUserWhs>().eq("WORK_CODE", userId));
        if (array.size() > 0){
            for (int i = 0; i< array.size(); i++){
                JSONObject doc = array.getJSONObject(i);
                SpmsUserWhs userWhs = new SpmsUserWhs();
                userWhs.setUserId(userId);
                userWhs.setWerks(doc.getString("werks"));
                userWhs.setWhsLocationCode(doc.getString("whsLocationCode"));
                userWhsMapper.insert(userWhs);
            }
        }
    }
    void createUserWorkshop(JSONArray array, String userId){
        /** 创建用户-车间关系数据 */
        userWorkshopMapper.delete(new QueryWrapper<SpmsUserWorkshop>().eq("WORK_CODE", userId));
        if (array.size() > 0) {
            for (int i = 0; i< array.size(); i++) {
                JSONObject doc = array.getJSONObject(i);
                SpmsUserWorkshop userWorkshop = new SpmsUserWorkshop();
                userWorkshop.setUserId(userId);
                userWorkshop.setWerks(doc.getString("werks"));
                userWorkshop.setWorkshopCode(doc.getString("workshopCode"));
                userWorkshopMapper.insert(userWorkshop);
            }
        }
    }

    /** 更新用户登录密码 */
    @Override
    public ResponseResult updatePassword(String userId, String MDPassword) {
        if (userId == null || userId.length() == 0 || MDPassword.length() == 0){
            return ResponseResult.error("请求参数错误");
        }
        if (spmsUserMapper.updatePassword(userId, MDPassword) > 0){
            return ResponseResult.success();
        }
        return ResponseResult.error();
    }

    @Override
    public void oaCreateSpmsUser(Map<String, Object> map, String MDPassword) {
        SpmsUser spmsUser = new SpmsUser();
        spmsUser.setUserId(map.get("userId").toString());
        spmsUser.setWorkId(map.get("workId").toString());
        spmsUser.setLastName(map.get("lastName").toString());
        spmsUser.setTelephone(map.get("telephone").toString());
        spmsUser.setMobile(map.get("mobile").toString());
        spmsUser.setEmail(map.get("email").toString());
        spmsUser.setPositionId(map.get("positionId").toString());
        spmsUser.setPositionName(map.get("positionName").toString());
        spmsUser.setDeptId(map.get("deptId").toString());
        spmsUser.setDeptName(map.get("deptName").toString());
        spmsUser.setSubcompanyId(map.get("subcompanyId").toString());
        spmsUser.setSubcompanyName(map.get("subcompanyName").toString());
        spmsUser.setCompany(map.get("company").toString());
        spmsUser.setBranchPoint(map.get("branchPoint").toString());
        spmsUser.setBranchLine(map.get("branchLine").toString());
        spmsUser.setManagerId(map.get("managerId").toString());
        spmsUser.setManagerName(map.get("managerName").toString());
        spmsUser.setOaStatus(map.get("oaStatus").toString());
        spmsUser.setLoginPassword(MDPassword);
        spmsUser.setSpmsStatus("1");
        this.baseMapper.insert(spmsUser);
    }

    @Override
    public ResponseResult updateSpmsUserInfo(Map<String, Object> map) {
        if (null == map || map.size() == 0){
            return ResponseResult.error("请求参数不能为空");
        }
        QueryWrapper<SpmsUser> queryWrapper = new QueryWrapper<SpmsUser>().eq("WORK_CODE", map.get("userId").toString());
        SpmsUser spmsUser = new SpmsUser();
        spmsUser.setWorkId(map.get("workId").toString());
        spmsUser.setLastName(map.get("lastName").toString());
        spmsUser.setTelephone(map.get("telephone").toString());
        spmsUser.setMobile(map.get("mobile").toString());
        spmsUser.setEmail(map.get("email").toString());
        spmsUser.setPositionId(map.get("positionId").toString());
        spmsUser.setPositionName(map.get("positionName").toString());
        spmsUser.setDeptId(map.get("deptId").toString());
        spmsUser.setDeptName(map.get("deptName").toString());
        spmsUser.setSubcompanyId(map.get("subcompanyId").toString());
        spmsUser.setSubcompanyName(map.get("subcompanyName").toString());
        spmsUser.setCompany(map.get("company").toString());
        spmsUser.setBranchPoint(map.get("branchPoint").toString());
        spmsUser.setBranchLine(map.get("branchLine").toString());
        spmsUser.setManagerId(map.get("managerId").toString());
        spmsUser.setManagerName(map.get("managerName").toString());
        spmsUser.setOaStatus(map.get("oaStatus").toString());
        int resp = this.baseMapper.update(spmsUser, queryWrapper);
        if (resp <= 0){
            return ResponseResult.error("更新失败");
        }
        return ResponseResult.success().add("spmsUser", this.baseMapper.selectOne(queryWrapper));
    }
}
